//
//  MyTool.swift
//  Unibet
//
//  Created by HaoSheng on 2020/4/21.
//  Copyright © 2020 蜗牛. All rights reserved.
//

import UIKit
import CoreLocation
import os.log


public func debugLog(_ message: String) {
    #if DEBUG
    os_log("%@", log: .default, type: .debug, message)
    #endif
}


public typealias Block = ()->Void


/// 当前版本号
public  var Version: String? {
    return Bundle.main.infoDictionary?["CFBundleShortVersionString"] as? String
}


//MARK: - 系统高度
/// 屏幕宽
@MainActor
public let MainWidth = UIScreen.main.bounds.width

/// 屏幕高
@MainActor
public let MainHeight = UIScreen.main.bounds.height

/// 导航栏高度
@MainActor
public let NavBarHeight = getCurrentVC.navigationController?.navigationBar.frame.size.height ?? 0

/// 状态栏高度
@MainActor
public var StatusHeight : CGFloat{
    if #available(iOS 13.0, *) {
        let scene = UIApplication.shared.connectedScenes.first
        guard let windowScene = scene as? UIWindowScene else { return 0 }
        guard let statusBarManager = windowScene.statusBarManager else { return 0 }
        return statusBarManager.statusBarFrame.height
//        return getWindow.windowScene?.statusBarManager?.statusBarFrame.height ?? 0
    }
    return UIApplication.shared.statusBarFrame.size.height
}

/// TabBar高度
@MainActor
public var TabBarHeight = getCurrentVC.tabBarController?.tabBar.frame.size.height ?? 0
    
///  导航栏+状态栏高度
@MainActor
public let NavBarAndStatusHeight = NavBarHeight + StatusHeight

/// 获取底部安全高度
@MainActor
@available(iOS 11.0, *)
public var bottomSafeArea = UIApplication.shared.windows.first?.safeAreaInsets.bottom ?? 0

//MARK: - 像素比例

/// 像素比
@MainActor
public let KWIDTH = UIScreen.main.bounds.width/375

//MARK: - 字号

/// 设置字号
@MainActor public func KFONT(font:CGFloat) -> UIFont{
    return UIFont.systemFont(ofSize: KWIDTH*font)
}


public class UNTool: NSObject {
    
// MARK: - NSTime  GDC
    public typealias Task = (_ cancel: Bool) -> Void
    /// 代码延迟运行
    ///
    /// - Parameters:
    ///   - delayTime: 延时时间。比如：.seconds(5)、.milliseconds(500)
    ///   - qosClass: 要使用的全局QOS类（默认为 nil，表示主线程）
    ///   - task: 延迟运行的代码
    /// - Returns: Task?
    @discardableResult
    public static func bk_delay(by delayTime: TimeInterval, qosClass: DispatchQoS.QoSClass? = nil, _ task: @escaping () -> Void) -> Task? {
        
        func dispatch_later(block: @escaping () -> Void) {
            let dispatchQueue = qosClass != nil ? DispatchQueue.global(qos: qosClass!) : .main
            dispatchQueue.asyncAfter(deadline: .now() + delayTime, execute: block)
        }
        
        var closure: (() -> Void)? = task
        var result: Task?
        
        let delayedClosure: Task = { cancel in
            if let internalClosure = closure {
                if !cancel {
                    DispatchQueue.main.async(execute: internalClosure)
                }
            }
            closure = nil
            result = nil
        }
        
        result = delayedClosure
        
        dispatch_later {
            if let delayedClosure = result {
                delayedClosure(false)
            }
        }
        
        return result
        
    }

    /// 取消代码延时运行
    public func delayCancel(_ task: Task?) {
        task?(true)
    }
    
    
    
// MARK: - 富文本
    
    ///设置字体和字体颜色 totalString完整的字符串 subString需要修改的字符串
    public static func changeFontColor(totalString: String, range: NSRange, font: UIFont, textColor: UIColor)-> NSMutableAttributedString {
        let attStr = NSMutableAttributedString.init(string: totalString)
        attStr.addAttributes([NSAttributedString.Key.foregroundColor: textColor, NSAttributedString.Key.font: font], range: range)
        return attStr
    }
    
    ///设置字体
    public static func changFont(string: String,font:UIFont,ranges:Array<NSRange>)->NSMutableAttributedString{
        let attStr = NSMutableAttributedString.init(string: string)
        
        for range in ranges {
            attStr.addAttributes([NSAttributedString.Key.font: font], range: range)
        }
        
        return attStr
    }
    
    ///设置字体颜色 string完整的字符串
    public static func changeColors(string: String,color:UIColor,ranges: Array<NSRange>)-> NSMutableAttributedString {
        
        let attStr = NSMutableAttributedString.init(string: string)
        
        for range in ranges {
            attStr.addAttributes([NSAttributedString.Key.foregroundColor: color], range: range)
        }
        
        return attStr
    }
    
    
    
    public typealias stringFromAttributeType = (key:NSAttributedString.Key,keyvalue:Any,range:NSRange)
    
    ///自由设置字体和字体颜色
    public static func stringFromAttributes(string: String ,attributes:[stringFromAttributeType]) -> NSMutableAttributedString {
        let attStr = NSMutableAttributedString.init(string: string)
        
        for attribute in attributes{
            attStr.addAttributes([attribute.key: attribute.keyvalue], range: attribute.range)
        }
        
        return attStr
    }
    
    
    
// MARK: - 十六进制的字符串转成数字
    ///十六进制的字符串转成数字
    public static func hexStringToInt(from:String) -> Int {
        let str = from.uppercased()
        var sum = 0
        for i in str.utf8 {
            sum = sum * 16 + Int(i) - 48 // 0-9 从48开始
            if i >= 65 {                 // A-Z 从65开始，但有初始值10，所以应该是减去55
                sum -= 7
            }
        }
        return sum
    }
    
    
// MARK: - 保存图片到沙盒
    ///保存图片至沙盒
    public static func saveImage(currentImage: UIImage, imageName: String) ->String{
        if let imageData = currentImage.jpegData(compressionQuality: 1) as NSData? {
            let fullPath = NSHomeDirectory().appending("/Documents/").appending(imageName)
            imageData.write(toFile: fullPath, atomically: true)
            return fullPath
        }
        return ""
    }
    
    
    
    /*
// MARK: - 下载图片
     public static func loadImage(url:String,dblock: @escaping (_ img:UIImage)->Void){
        SDWebImageManager.shared.loadImage(with: URL.init(string: url), options: SDWebImageOptions.allowInvalidSSLCertificates) { receivedSize, expectedSize, targetUrl in
            //下载进度
        } completed: { image, data, error, cacheType, finished, imageURL in
            //下载完成
            if image != nil {
                dblock(image!)
            }
        }
    }
    
    
    
    
     
    
    
// MARK: - 弹窗获取图片
     public typealias imageBlock = (_ image:UIImage) -> Void
    ///获取一张图片
     public static func addOneImage(dblock: @escaping imageBlock){
        
        UNActionSheetView.showActionSheet(withTitle: "添加图片", cancelButtonTitle: "取消", destructiveButtonTitle: nil, otherButtonTitles: ["拍照","相册中获取"]) { (actionSheet, index) in
            if index == 1 {//去拍照
                UNPhonePicker.shareManager.imagePicker {  (image, url, asset) in
                    if image == nil {
                        HUD.showHint(hint: "图片获取失败！")
                    }else{
                        dblock(image!)
                    }
                }

            }else if index == 2 {//去相册
                UNPhonePicker.shareManager.pickerPhoto { image, _, _ in
                    if image == nil {
                        HUD.showHint(hint: "图片获取失败！")
                    }else{
                        dblock(image!)
                    }
                }
            }
        }
    }
    
     */
    
    
    
// MARK: - 检查定位权限
    ///检查提示定位权限
    @MainActor public static func showEventsAcessDeniedAlert() {
        
        let status: CLAuthorizationStatus
        
        if #available(iOS 14.0, *) {
            let manager = CLLocationManager()
            status = manager.authorizationStatus  // iOS 14+ 使用实例属性
        } else {
            status = CLLocationManager.authorizationStatus()  // 旧版本保留类方法
        }
        
        if(status != .denied) {

            print("应用拥有定位权限")

        }else {

            let alertController = UIAlertController(title: "打开定位开关",message: "定位服务未开启,请进入系统设置>隐私>定位服务中打开开关,并允许App使用定位服务",preferredStyle: .alert)

                let settingsAction = UIAlertAction(title: "去设置", style: .default) { (alertAction) in

                if let appSettings = NSURL(string: UIApplication.openSettingsURLString) {
                    
                    UIApplication.shared.open(appSettings as URL, options: [:], completionHandler: nil)
                }
            }

            alertController.addAction(settingsAction)

            let cancelAction = UIAlertAction(title: "取消", style: .cancel, handler: nil)

            alertController.addAction(cancelAction)

            getCurrentVC.present(alertController, animated: true, completion: nil)
    
        }
    }
    
    
    
}


///系统弹窗
@MainActor public func showAlertController(title:String,message: String = "",okTitle: String = "确定",noTitle:String = "取消",titleFont:UIFont = .systemFont(ofSize: 18) ,messageFont: UIFont = .systemFont(ofSize: 14) ,titleColor:UIColor = .black ,messageColor: UIColor = UIColor.FromHex(rgb: 0x999999),canceTitleColor: UIColor = .blue , okTitleColor: UIColor = .red ,okBlock: @escaping () -> Void = {},noBlock: @escaping () -> Void = {}){
    
    let alert = UIAlertController(title: title, message: message, preferredStyle: .alert)
    let  titleAttribute =  NSMutableAttributedString . init (string:  alert.title!)
    titleAttribute.addAttributes([NSAttributedString.Key.font:titleFont,NSAttributedString.Key.foregroundColor: titleColor],range: NSMakeRange (0, ( alert.title?.count)!))
    alert.setValue(titleAttribute, forKey:  "attributedTitle" )

     let  messageAttribute =  NSMutableAttributedString . init (string:  alert.message!)
    messageAttribute.addAttributes([NSAttributedString.Key.font:messageFont,NSAttributedString.Key.foregroundColor: messageColor],range: NSMakeRange (0, ( alert.message?.count)!))
    alert.setValue(messageAttribute, forKey:  "attributedMessage" )
    
    
    let canceAction = UIAlertAction(title: noTitle, style: .cancel) { action in
        noBlock()
    }
    canceAction.setValue(canceTitleColor, forKey: "_titleTextColor")
    
    let Action = UIAlertAction(title: okTitle, style: .default) { (action) in
        
        okBlock()
        
    }
    Action.setValue(okTitleColor, forKey: "_titleTextColor")
    
    alert.addAction(Action)
    
    alert.addAction(canceAction)
    
    getCurrentVC.present(alert, animated: true, completion: nil)
    
}


// MARK: - 获取键盘mode
///获取emoji表情键盘InputMode
@MainActor public func getEmojiInputMode() ->UITextInputMode{
    
    for mode in UITextInputMode.activeInputModes {
        
        if mode.primaryLanguage == "emoji" {
            return mode
        }
    }
    return UITextInputMode.init()
}


// MARK: - 正则
///正则
public func regular(string: String ,regularStr:String)->[NSTextCheckingResult]{
    let range = NSRange(location: 0, length: string.count)
    let regex = try! NSRegularExpression(pattern: regularStr, options: [.caseInsensitive])
    // 从指定字符串中取出所有匹配规则的字符串的结果集，返回的是[NSTextCheckingResult]类型
    let resArray = regex.matches(in: string, options: [.reportProgress], range: range)
    return resArray
}

///正则获取话题
public func huatiRegular(string: String)->[NSTextCheckingResult]{
    // 匹配 ## 的
    return regular(string: string, regularStr: "#[^#]+#")
}


// MARK: - 打电话
@MainActor public func callPhone(phone:String,block: Block? = nil){
    let phone = "telprompt://" + phone
    if UIApplication.shared.canOpenURL(URL(string: phone)!) {
        UIApplication.shared.open(URL(string: phone)!, options: [:]) { (boo) in
            if let block = block {
                block()
            }
        }
    }
}







